package br.com.dispositivosmoveis.acompanhamentodeconta.repository;

import java.util.ArrayList;
import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import br.com.dispositivosmoveis.acompanhamentodeconta.abstracts.CrudRepository;
import br.com.dispositivosmoveis.acompanhamentodeconta.abstracts.ItemRepository;
import br.com.dispositivosmoveis.acompanhamentodeconta.model.Item;
import br.com.dispositivosmoveis.acompanhamentodeconta.model.Pedido;

public class ItemRepositoryImpl extends CrudRepository<Item> implements
		ItemRepository {

	@Override
	public Long insert(Item entity) throws SQLiteConstraintException, Exception {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void update(ContentValues values, String whereClause,
			String... whereArgs) throws SQLiteConstraintException, Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public Item obtain(int id) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Item> getAll() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Item> findyByComanda(Integer idComanda) {
		StringBuilder query = new StringBuilder("SELECT ");
		query.append("i." + Item.COLUMN_ID + ", ");
		query.append("i." + Item.COLUMN_DESCRICAO + ", ");
		query.append("i." + Item.COLUMN_VALOR + " ");
		query.append("FROM " + Item.TABLE_NAME + " i ");
		query.append("JOIN " + Pedido.TABLE_NAME + " p ");
		query.append("ON i." + Item.COLUMN_ID + " = p.");
		query.append(Pedido.COLUMN_ID_ITEM + " WHERE ");
		query.append("p." + Pedido.COLUMN_ID_COMANDA + " = ? ");

		Cursor cursor = this.getReadableDatabase().rawQuery(query.toString(),
				new String[] { String.valueOf(idComanda) });

		cursor.moveToFirst();

		List<Item> itens = new ArrayList<Item>();

		for (int i = 0; i < cursor.getCount(); i++) {
			Item item = new Item();
			item.setId(cursor.getInt(cursor.getColumnIndex(Item.COLUMN_ID)));
			item.setDescricao(cursor.getString(cursor
					.getColumnIndex(Item.COLUMN_DESCRICAO)));
			item.setValor(cursor.getDouble(cursor
					.getColumnIndex(Item.COLUMN_VALOR)));

			itens.add(item);

			cursor.moveToNext();
		}
		cursor.close();
		return itens;
	}

}
